class Customer < ActiveRecord::Base

  attr_protected []
	
	belongs_to :created_by, :class_name => 'User', :foreign_key => 'created_by_id'
	belongs_to :updated_by, :class_name => 'User', :foreign_key => 'updated_by_id'
	has_many :phones, :class_name => "ContactWay::Phone", :foreign_key => "customer_id", :order => 'id asc'
	has_many :ims, :class_name => "ContactWay::Im", :foreign_key => "customer_id", :order => 'id asc'
	has_many :emails, :class_name => "ContactWay::Email", :foreign_key => "customer_id", :order => 'id asc'
	has_many :web_sites, :class_name => "ContactWay::WebSite", :foreign_key => "customer_id", :order => 'id asc'
	has_many :addresses, :class_name => "ContactWay::Address", :foreign_key => "customer_id", :order => 'id asc'
	has_many :contact_records, :order => 'created_at desc'  
  has_many :customer_visible_to_users
  has_many :customer_visible_to_groups
  has_many :users, :through => :customer_visible_to_users
  has_many :groups, :through => :customer_visible_to_groups
  belongs_to :enterprise
  has_many :customer_tags, :dependent => :destroy
  has_many :tags, :through => :customer_tags
    
	validates :first_name,
		:last_name,
		:presence => true  

	accepts_nested_attributes_for :phones,
		:ims,
		:emails,
		:addresses,
		:web_sites,
    :allow_destroy => true,
    :reject_if => proc { |attributes| attributes['way'].blank? }
    
  accepts_nested_attributes_for :customer_visible_to_groups,
    :allow_destroy => true,
    :reject_if => proc { |attributes| attributes['group_id'].blank? }
    
  accepts_nested_attributes_for :customer_visible_to_users,
    :allow_destroy => true,
    :reject_if => proc { |attributes| attributes['user_id'].blank? }
		
	default_scope lambda { 
	  where( :enterprise_id => Enterprise.current_id ).try(
	    User.current.is_admin? ? 'escaped_visible_scope' : 'by_visible_scope'
	  )
  }
	
	scope :by_visible_scope, lambda { 
    where(
      "(visible_scope = ? and created_by_id = ? ) or (visible_scope = ? ) or (visible_scope = ? and id in (?) ) or (visible_scope = ? and id in (?))",
      'myself',
      User.current_id,
      'everyone',
      'groups',
      # 所有
      CustomerVisibleToGroup.select('DISTINCT  customer_id').where( 'group_id in (?)', User.current.group_ids.uniq).each_with_object([]) {|visible,customer_ids| customer_ids << visible.customer_id },
      'users',
      CustomerVisibleToUser.select('DISTINCT customer_id').where( 'user_id = ?', User.current_id).each_with_object([]) {|visible,customer_ids| customer_ids << visible.customer_id }
    )    
  }
  
  scope :escaped_visible_scope, lambda { where('visible_scope is not null') }

  scope :active, lambda { where(:status => 'active') }

  scope :blank_out, lambda { where(:status => 'blank_out') }
  
  scope :escaped_visible_scope, lambda {  }

  scope :by_tag_id, lambda {|tag_id| where('customer_tags.tag_id = ?', tag_id).includes(:customer_tags) }

  scope :untagged, lambda {|tag_id| 
    where(['customers.id not in (?)', CustomerTag.select('distinct customer_id').collect {|ct|  ct.customer_id } + [-1] ]) 
  }

  # 有进展
  scope :contacted_on_in_near_one_week, lambda{ where( 'contacted_on >=? and contacted_on <= ?', 1.weeks.ago, Time.now ) }
  scope :contacted_on_in_near_half_month, lambda{ where( 'contacted_on >=? and contacted_on <= ?', 15.days.ago, Time.now ) }
  scope :contacted_on_in_near_one_month, lambda{ where( 'contacted_on >=? and contacted_on <= ?', 1.months.ago, Time.now ) }
  scope :contacted_on_in_pass_one_month, lambda{ where( 'contacted_on <= ?', 1.months.ago ) }

  # 无进展
  scope :no_contacted_on_in_pass_one_week, lambda{ where( 'contacted_on <= ?', 1.weeks.ago ) }
  scope :no_contacted_on_in_pass_half_month, lambda{ where( 'contacted_on <= ?', 15.days.ago) }
  scope :no_contacted_on_in_pass_one_month, lambda{ where( 'contacted_on <= ?', 1.months.ago) }
		
	before_create do |customer|
		customer.created_by = User.current
  end	
  
  before_update do |customer|
  	customer.updated_by = User.current  	
	end

  before_save do |customer|
    customer.reset_key_words
  end
	
	after_save do |customer|
	  customer.groups.clear if not customer.visible_scope.groups?
  	customer.users.clear if not customer.visible_scope.users?
  end
	
	def full_name
		"#{first_name}#{last_name}"
	end
	
	def visible_scope
	  ActiveSupport::StringInquirer.new(self[:visible_scope])
  end
  
  # 谁可见该单
  def who_can_see
    case
    when visible_scope.myself?
      [User.current]
    when visible_scope.everyone?
      Enterprise.current.users
    when visible_scope.groups?
      customer_visible_to_groups.each_with_object([Enterprise.current.admin]) do |customer_visible_to_group, users|
        customer_visible_to_group.group.users.each do |user|
          users << user if not users.include?(user)
        end
      end
    when visible_scope.users?
      customer_visible_to_users.each_with_object([Enterprise.current.admin]) do |customer_visible_to_user, users|
        users << customer_visible_to_user.user if not users.include?(customer_visible_to_user.user)
      end
    else
      raise "不支持的类型:#{visible_scope}"
    end    
  end

  def ways
    (phones + ims + emails + web_sites + addresses).each_with_object([]) do |w, ways|
      ways << "#{w.type_name}:#{w.way}"
    end
  end

  def ways_by_key_word(key_word)
    ContactWay.where(:customer_id => id).where(['way like ?', "%#{key_word}%"]).each_with_object([]) do |w, ways|
      ways << "#{w.type_name}:#{w.way}"
    end
  end

  def reset_key_words
    self.key_words = full_name + ',' + title + ',' + organization + ',' + ways.join(',')
  end

  def active!
    status! 'active'
  end

  def blank_out!
    status! 'blank_out'
  end

  def status!(new_status)
    self.status = new_status
    save(:validate => false)
  end
end
